// 发版刷新页面，根据监测上传文件实现刷新
import Data from "xe-utils/date";

let lastSrcs;
//获取到js名字
const scriptReg = /\<script.*src=["'](?<src>[^"']+)/gm;

//获取最新页面中的script链接
async function extractNewScripts() {
    // _timestamp避免缓存，获取当前时间戳
    const html = await fetch('/?_timestamp=' + Data.now()).then((resp) =>
        resp.text()
    );
    // console.log("html",html)
    scriptReg.lastIndex = 0;
    let result = [];
    let match;
    while ((match = scriptReg.exec(html))) {
      // console.log("match.groups",match.groups)
        result.push(match.groups.src);
    }
    return result;
}

//进行js文件命名对比
async function needUpdate() {
    const newScripts = await extractNewScripts();
    // console.log("旧版js1",lastSrcs)
    // console.log("新版js1",newScripts)
    if (!lastSrcs) {
        lastSrcs = newScripts;
        return false;
    }
    let result = false;
    if (lastSrcs.length !== newScripts.length) {
        result = true;
    }
    for (let i = 0; i < lastSrcs.length; i++) {
        if (lastSrcs[i] !== newScripts[i]) {
            result = true;
            break;
        }
    }
    lastSrcs = newScripts;
    return result;
}
//每五秒进行一次比对
const DURATION = 5000;
//出现的弹窗里的文字
function autoRefresh() {
    setTimeout(async () => {
        const willUpdate = await needUpdate();
        if (willUpdate) {
            const result = confirm('有新功能发布，请点击确定刷新页面！');
                if (result) {
                    location.reload(true);
                }
        }
        autoRefresh();
    },DURATION);
}

autoRefresh();
